<script setup>
//引用区域
import { ref, onMounted, watch } from "vue";
import {
  queryEmpListApi,
  addEmpInfoApi,
  queryEmpByIdApi,
  updateEmpByIdApi,
  deleteEmpByIdApi,
} from "@/api/emp.js";
import { getDeptListApi as queryAllDeptList } from "@/api/dept.js";
import { ElMessage, ElMessageBox } from "element-plus";

//申明token
const token = ref("");

//获取token
const getToken = () => {
  console.log("getToken");
  const loginUser = JSON.parse(localStorage.getItem("loginUser"));
  console.log(loginUser);
  if (loginUser) {
    token.value = loginUser.token;
    console.log(token);
  }
};

//钩子函数区域
onMounted(() => {
  getToken();
  search();
  queryDeptList();
});

//表单校验规则
//表单校验规则
const rules = ref({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 2,
      max: 20,
      message: "用户名长度应在2到20个字符之间",
      trigger: "blur",
    },
  ],
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    {
      min: 2,
      max: 10,
      message: "姓名长度应在2到10个字符之间",
      trigger: "blur",
    },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    /**
     * 正则表达式 校验手机号 校验规则
     * 1.开头必须是1
     * 2.第二位必须是数字
     * 3.剩余11位必须是数字
     */
    { pattern: /^1\d{10}$/, message: "请输入有效的手机号", trigger: "blur" },
  ],
});

//员工经历明细
const addExpListItem = () => {
  console.log("addExpListItem");
  employee.value.exprList.push({
    company: "",
    job: "",
    begin: "",
    end: "",
    exprDate: [],
  });
};

const delExprList = (index) => {
  console.log("delExprList");
  employee.value.exprList.splice(index, 1);
};

const searchForm = ref({
  name: "",
  gender: "",
  entryTime: [],
  begin: "",
  end: "",
});
//分页条数据 对象 start
const pageSize = ref(10);
const currentPage = ref(1);
const small = ref(false);
const background = ref(true);
const totalData = ref(300);

//当前显示数量改变方法
const handleSizeChange = async (val) => {
  console.log(`每页展示：${val}`);
  search();
};
//当前页码改变方法
const handleCurrentChange = async (val) => {
  console.log(`当前页是: ${val}`);
  search();
};
//分页条数据 对象 end

//通过watch监听 entryTime 监听到变化时，自动触发
//对象属性值 监听
watch(
  () => searchForm.value.entryTime,
  (newValue, oldValue) => {
    //首先进行判空操作  entry 是数组 所以里边长度是2
    if (newValue.length == 2) {
      console.log(searchForm.value);
      console.log(newValue);
      console.log(oldValue);
      searchForm.value.begin = newValue[0];
      searchForm.value.end = newValue[1];
      console.log(searchForm.value);
    } else {
      searchForm.value.begin = "";
      searchForm.value.end = "";
    }
  }
);

//empListData
const EmpListData = ref([]);
const search = async () => {
  const result = await queryEmpListApi(
    searchForm.value.name,
    searchForm.value.gender,
    searchForm.value.begin,
    searchForm.value.end,
    currentPage.value,
    pageSize.value
  );
  if (result.code) {
    console.log(result.data);
    EmpListData.value = result.data.rows;
    totalData.value = result.data.total;
  } else {
    alert("查询失败");
  }
};

const clearData = () => {
  searchForm.value = {
    name: "",
    gender: "",
    entryTime: [],
    begin: "",
    end: "",
  };
  search();
};

const onSubmit = () => {
  console.log(searchForm.value);
  search();
  search();
};

//新增/修改表单
const employeeFormRef = ref();
const employee = ref({
  username: "",
  name: "",
  gender: "",
  phone: "",
  job: "",
  salary: "",
  deptId: "",
  entryDate: "",
  image: "",
  exprList: [],
});

// 控制弹窗
const dialogVisible = ref(false);
const dialogTitle = ref("");

//文件上传
const imageUrl = ref("");
// 图片上传成功后触发
const handleAvatarSuccess = (response) => {
  imageUrl.value = response.data;
  employee.value.image = imageUrl.value;
};

//性别数值定义
//职位列表数据
const jobs = ref([
  { name: "班主任", value: 1 },
  { name: "讲师", value: 2 },
  { name: "学工主管", value: 3 },
  { name: "教研主管", value: 4 },
  { name: "咨询师", value: 5 },
  { name: "其他", value: 6 },
]);
//性别列表数据
const genders = ref([
  { name: "男", value: 1 },
  { name: "女", value: 2 },
]);

//部门列表数据
const deptList = ref([]);

// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("只支持上传图片");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("只能上传10M以内图片");
    return false;
  }
  return true;
};

const addEmp = () => {
  dialogVisible.value = true;
  dialogTitle.value = "新增员工";
  imageUrl.value = "";
  employee.value = {
    username: "",
    name: "",
    gender: "",
    phone: "",
    job: "",
    salary: "",
    deptId: "",
    entryDate: "",
    image: "",
    exprList: [],
  };

  //清空上次表单校验信息
  if (employeeFormRef.value) {
    employeeFormRef.value.resetFields();
  }
};

const queryDeptList = async () => {
  const result = await queryAllDeptList();
  deptList.value = result.data;
};

//侦听工作信息
watch(
  () => employee.value.exprList,
  (newValue, oldValue) => {
    console.log("watch");
    console.log(newValue);
    console.log(oldValue);
    if (Array.isArray(newValue) && newValue.length > 0) {
      newValue.forEach((expr) => {
        if (Array.isArray(expr.exprDate) && expr.exprDate.length === 2) {
          expr.begin = expr.exprDate[0];
          expr.end = expr.exprDate[1];
        }
      });
    }
  },
  { deep: true } // 深度监听以确保内部对象的变化也能触发
);

const save = async () => {
  if (!employeeFormRef.value) {
    return;
  }
  //开始校验表单项
  employeeFormRef.value.validate(async (valid) => {
    if (valid) {
      let result;
      if (employee.value.id) {
        console.log("update");
        result = await updateEmpByIdApi(employee.value);
      } else {
        console.log("save");
        result = await addEmpInfoApi(employee.value);
      }

      if (result.code) {
        ElMessage.success("保存成功");
        dialogVisible.value = false;
        search();
      } else {
        ElMessage.error(result.msg);
      }
    } else {
      ElMessage.error("表单校验失败失败");
    }
  });
};

const editOpen = async (id) => {
  const result = await queryEmpByIdApi(id);
  if (result.code) {
    dialogVisible.value = true;
    dialogTitle.value = "修改员工";
    employee.value = result.data;
    imageUrl.value = result.data.image;
    //对工作经历做处理
    let exprList = employee.value.exprList;
    if (exprList && exprList.length > 0) {
      exprList.forEach((expr) => {
        expr.exprDate = [expr.begin, expr.end];
      });
    }
  }
};

const delById = (id) => {
  //弹出消息确认框
  ElMessageBox.confirm("请确认是否删除?", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  }) //点击确认 then
    .then(async () => {
      //删除
      const result = await deleteEmpByIdApi(id);
      if (result.code) {
        //提示结果
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        //回调查询方法
        search();
      } else {
        ElMessage({
          type: "error",
          message: result.msg,
        });
      }
    }) //点击取消
    .catch(() => {
      ElMessage({
        type: "info",
        message: "您以取消删除",
      });
    });
};

//实时记录勾选的员工id
const checkIds = ref([]);

//复选框发生变化触发 --> val 当前选中的信息数组
const handleSelectionChange = (val) => {
  console.log(val);
  //这样写不行
  // val.forEach((emp) => {
  //   checkIds.value.push(emp.id);
  // });
  checkIds.value = val.map((emp) => emp.id);
};

//批量删除员工
const deleteBatch = () => {
  console.log(checkIds.value);
  //弹出消息确认框
  ElMessageBox.confirm(`请确认是否删除?[${checkIds.value}]`, "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  }) //点击确认 then
    .then(async () => {
      if (checkIds.value && checkIds.value.length > 0) {
        //删除
        const result = await deleteEmpByIdApi(checkIds.value);
        if (result.code) {
          //提示结果
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          //回调查询方法
          search();
        } else {
          ElMessage({
            type: "error",
            message: result.msg,
          });
        }
      } else {
        ElMessage({
          type: "error",
          message: "请选择要删除的员工,目前无选择",
        });
      }
    }) //点击取消
    .catch(() => {
      ElMessage({
        type: "info",
        message: "您以取消删除",
      });
    });
};
</script>

<template>
  <!-- 搜索栏区域  start -->
  <!-- 标题抬头 start  -->
  <div class="placeholder">&nbsp;</div>
  <h1 class="inline-title">&nbsp;&nbsp;&nbsp;员工管理</h1>
  <!-- 测试使用选中员工id {{ checkIds }} -->
  <!-- 标题抬头 end -->
  <!-- 测试数据使用--dev -->
  <!-- {{ searchForm }} -->
  <!-- 测试数据使用--dev -->
  <!-- 搜索栏表单区域  start -->
  <el-form :inline="true" :model="searchForm" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input
        v-model="searchForm.name"
        placeholder="请输入员工姓名"
        clearable
      />
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="searchForm.gender" placeholder="请选择性别" clearable>
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
    </el-form-item>
    <el-form-item label="入职时间">
      <div class="block">
        <el-date-picker
          v-model="searchForm.entryTime"
          type="daterange"
          start-placeholder="开始日期"
          range-separator="到"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">查询</el-button>
      <el-button type="info" @click="clearData">清空</el-button>
    </el-form-item>
  </el-form>
  <!-- 搜索栏表单区域  end -->

  <!-- 按钮操作区域 start  -->
  <div>
    <el-button type="primary" @click="addEmp"
      ><el-icon><Plus /></el-icon>&nbsp;新增员工</el-button
    >
    <el-button type="danger" @click="deleteBatch"
      ><el-icon><Delete /></el-icon>&nbsp;批量删除</el-button
    >
  </div>
  <!-- 按钮操作区域 end  -->

  <!-- 数据展示区域 start  -->
  <div class="container">
    <el-table
      :data="EmpListData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column prop="name" label="姓名" width="100" align="center" />
      <el-table-column prop="gender" label="性别" width="60" align="center">
        <template #default="scope">
          <!-- <span v-if="scope.row.gender == 1">男</span>
          <span v-else>女</span> -->
          {{ scope.row.gender == 1 ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" width="100">
        <template #default="scope">
          <img
            :src="scope.row.image"
            alt="头像"
            style="width: 50px; height: 40px"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="deptName"
        label="所属部门"
        align="center"
        width="100"
      />
      <el-table-column prop="job" label="职位" align="center" width="120">
        <template #default="scope">
          <span v-if="scope.row.job == 1">班主任</span>
          <span v-else-if="scope.row.job == 2">讲师</span>
          <span v-else-if="scope.row.job == 3">学工主管</span>
          <span v-else-if="scope.row.job == 4">教研主管</span>
          <span v-else-if="scope.row.job == 5">咨询师</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="entryDate"
        label="入职日期"
        align="center"
        width="120"
      />
      <el-table-column
        prop="updateTime"
        label="最后操作时间"
        align="center"
        width="200"
      />
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="editOpen(scope.row.id)"
          >
            <el-icon><EditPen /></el-icon>&nbsp;编辑
          </el-button>
          <el-button type="danger" size="small" @click="delById(scope.row.id)">
            <el-icon><Delete /></el-icon>&nbsp;删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 数据展示区域 end  -->

  <!-- 分页条 start  -->
  <!-- 测试使用 -->
  <!-- {{ currentPage }} ： {{ pageSize }} -->
  <!-- 测试使用 -->
  <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[5, 10, 20, 30, 50, 100]"
    :small="small"
    :background="background"
    layout="total, sizes, prev, pager, next, jumper"
    :total="totalData"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <!--  分页条 end  -->

  <!-- 搜索栏区域  end -->

  <!-- 新增员工界面  start -->
  <!-- 员工基本信息界面  start -->
  <!-- 新增员工/修改员工对话框 start -->
  <el-dialog v-model="dialogVisible">
    <div class="boldTitle">
      <div class="placeholder">&nbsp;</div>
      {{ dialogTitle }}
    </div>
    <el-form
      ref="employeeFormRef"
      :model="employee"
      label-width="80px"
      :rules="rules"
    >
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="employee.username"
              placeholder="请输入员工用户名，2-20个字"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="employee.name"
              placeholder="请输入员工姓名，2-10个字"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select
              v-model="employee.gender"
              placeholder="请选择性别"
              style="width: 100%"
            >
              <!-- <el-option label="男" value="1"></el-option>
              <el-option label="女" value="2"></el-option> -->

              <!-- 优化数据展示 -->
              <el-option
                v-for="gender in genders"
                :key="gender.value"
                :label="gender.name"
                :value="gender.value"
              ></el-option>
              <!-- 优化数据展示 -->
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="employee.phone"
              placeholder="请输入员工手机号"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select
              v-model="employee.job"
              placeholder="请选择职位"
              style="width: 100%"
            >
              <el-option
                v-for="job in jobs"
                :key="job.value"
                :label="job.name"
                :value="job.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input
              v-model="employee.salary"
              placeholder="请输入员工薪资"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select
              v-model="employee.deptId"
              placeholder="请选择部门"
              style="width: 100%"
            >
              <el-option
                v-for="dept in deptList"
                :key="dept.id"
                :label="dept.name"
                :value="dept.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker
              v-model="employee.entryDate"
              type="date"
              style="width: 100%"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :headers="{ token: token }"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 工作经历 -->
      <!-- 第六行 -->
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="工作经历">
            <el-button type="success" size="small" @click="addExpListItem"
              >+ 添加工作经历</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
      <!-- {{ employee }}  测试使用 -->
      <!-- 第七行 ...  工作经历 -->
      <el-row
        :gutter="3"
        v-for="(expr, index) in employee.exprList"
        :key="index"
      >
        <el-col :span="10">
          <el-form-item
            size="small"
            label="时间"
            label-width="80px"
            v-model="expr.exprDate"
          >
            <el-date-picker
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              v-model="expr.exprDate"
            ></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="公司" label-width="60px">
            <el-input
              v-model="expr.company"
              placeholder="请输入公司名称"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="职位" label-width="60px">
            <el-input placeholder="请输入职位" v-model="expr.job"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item size="small" label-width="0px">
            <el-button type="danger" @click="delExprList(index)"
              >删除</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 新增员工/修改员工对话框 end -->
  <!-- 员工基本信息界面  end -->

  <!-- 员工工作经历信息界面  start -->
  <!-- 员工工作经历信息界面  end -->

  <!-- 新增员工界面  end -->
</template>

<style scoped>
.placeholder {
  width: 5px;
  height: auto;
  background-color: blue;
  display: inline-block;
}

.inline-title {
  display: inline-block;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.container {
  margin: 20px 0;
}

.avatar {
  height: 40px;
}
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
.boldTitle {
  font-weight: bold;
  font-size: 20px;
  margin-top: 0px;
  margin-bottom: 30px;
}
</style>
